package com.dongdongshop.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.dongdongshop.common.UpLoadCommon;
import com.dongdongshop.data.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


@Controller

@RequestMapping("goodsImg")
public class GoodsImgUploadController {
    private Logger logger = LoggerFactory.getLogger(GoodsImgUploadController.class);
    @Autowired
    private UpLoadCommon upLoadCommon;
    @RequestMapping("upload")
    @ResponseBody
    public Result upload(@RequestParam("images") MultipartFile images) {

        // Endpoint以杭州为例，其它Region请按实际情况填写。

// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。

// <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        String objectName = images.getOriginalFilename();

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(upLoadCommon.getEndpoint(), upLoadCommon.getAccessKeyId(), upLoadCommon.getAccessKeySecret());

// 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
        String url = "";
        try {
            ossClient.putObject(upLoadCommon.getBucketName(), objectName, images.getInputStream());
            url = "http://"+upLoadCommon.getBucketName()+".oss-cn-beijing.aliyuncs.com/"+objectName;

        }catch (Exception e){

            return Result.fail();
        }

        ossClient.shutdown();
        return Result.ok().setInfo(url);
// 关闭OSSClient。

    }
}


